#include "widget_1.h"    //音乐播放
#include "ui_widget_1.h"

widget_1::widget_1(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::widget_1)
{
    ui->setupUi(this);


    background_main = new QLabel(this);
    QPixmap img_1(":/kk/Home/KK_1.png");
    background_main->setPixmap(img_1);
   // background_main->setGeometry(this->rect()); // 填满整个窗口
    background_main->setScaledContents(true);  // 自动拉伸适配窗口大小
    background_main->lower();                  // 将背景设置到最底层


    sql_init("Media_data.db");


    my_paly->setPlaylist(music_list);

   ui->verticalSlider->setMaximum(200);

    listWidget =  new QListWidget(this->ui->widget_tab);

    listWidget->setGeometry(this->rect()); // 填满整个窗口

    connect(listWidget, &QListWidget::itemClicked, this, &widget_1::play_music);

    up_data_list();

    connect(my_paly, &QMediaPlayer::mediaStatusChanged, this, [&](QMediaPlayer::MediaStatus status) {
        // 媒体缓冲完成
        ui->label_MediaName->setText(play_Media.name);
        if (status == QMediaPlayer::BufferedMedia) {
            qDebug() << "Media is buffered, ready to play!";
            qDebug() << formatTime(my_paly->duration());  // 显示时长
            Media_TimeMax = my_paly->duration();         // 获取媒体时长
            ui->horizontalSlider->setMaximum(Media_TimeMax);
            ui->label_end->setText(formatTime(my_paly->duration()));  // 更新结束时间标签
        }
        // 媒体播放完成
        if(ProgressBarDragState == false)
        if (status == QMediaPlayer::EndOfMedia) {
            qDebug() << "Playback finished!";
            int ID_temp = play_Media.ID + 1;  // 获取下一个媒体的 ID

            // 获取下一个媒体
            play_Media = select_MediaUrlID(ID_temp);

            if (!play_Media.Path.isEmpty())
            {  // 确保有下一个媒体路径
                my_paly->setMedia(play_Media.Path);  // 设置新媒体
                my_paly->play();  // 播放新媒体
            }
        }
    });
    connect(ui->horizontalSlider, &QSlider::sliderPressed, this, [&]() {
        ProgressBarDragState = true;  // 开始拖动
    });

    connect(ui->horizontalSlider, &QSlider::sliderReleased, this, [&]() {
        ProgressBarDragState = false;  // 停止拖动
        my_paly->setPosition(ui->horizontalSlider->value());  // 手动设置位置
        my_paly->play();

    });
    connect(my_paly, &QMediaPlayer::positionChanged, this, [=](qint64 position) {
        if(ProgressBarDragState == false)
        {
            qDebug() << "Current playback position:" << formatTime(position);
            ui->horizontalSlider->setValue(position);  // 更新进度条
            ui->label_start->setText(formatTime(position));  // 更新当前播放时间标签
        }
    });

    requestMusicId("林宥嘉-成全.mp3");
    ui->dockWidget->setTitleBarWidget(new QWidget());

}

widget_1::~widget_1()
{
    delete ui;

}
void widget_1::resizeEvent(QResizeEvent *event)
{
    QWidget::resizeEvent(event);            // 调用基类的 resizeEvent 方法
    background_main->setGeometry(this->rect());        // 根据窗口大小调整背景 QLabel 的尺寸
}


void widget_1::on_pushButton_clicked()
{
    if(false == PlayerStatus)
    {
        PlayerStatus=true;
        my_paly->play();
        ui->pushButton->setText("播放");
    }
     else if(true == PlayerStatus)
    {
        PlayerStatus=false;
        my_paly->pause();
         ui->pushButton->setText("停止");
    }


}

void widget_1::on_pushButton_2_clicked()
{

     ui-> dockWidget->setVisible(!( ui-> dockWidget->isVisible()));  // 显示 dockWidget

  // ui->  dockWidget->setVisible(false); // 隐藏 dockWidget
}

void widget_1::requestMusicId(QString str)
{
   // "http://music.163.com/api/search/get/web?csrf_token=hlpretag=&hlposttag=&s=周杰伦&type=1&offset=0&total=true&limit=10";
    QUrl tokenUrl("http://music.163.com/api/search/get/web");
    QUrlQuery query;
    query.addQueryItem("csrf_token", ""); // 如果需要，替换为空字符串
    query.addQueryItem("hlpretag", "");
    query.addQueryItem("hlposttag", "");
    query.addQueryItem("s", str);
    query.addQueryItem("type", "1");
    query.addQueryItem("offset", "0");
    query.addQueryItem("total", "true");
    query.addQueryItem("limit", "10");
    tokenUrl.setQuery(query);

    QNetworkRequest tokenRequest(tokenUrl);
    QNetworkReply *tokenReply = networkManager->get(tokenRequest);
    connect(tokenReply, &QNetworkReply::finished, this, &widget_1::onMusicCallback);

    qDebug() << "Access token request sent.";
}

void widget_1::onMusicCallback()
{
    QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender());
    if (!reply) return;

    if (reply->error() == QNetworkReply::NoError) {
        QByteArray response = reply->readAll();
        QJsonDocument doc = QJsonDocument::fromJson(response);

        qDebug() <<  QString::fromUtf8(response) ;
    } else {
        qDebug() << "Network error while fetching access token:" << reply->errorString();
    }

    reply->deleteLater();
}


void widget_1::on_pushButton_3_clicked()
{
    QStringList fileNames = QFileDialog::getOpenFileNames(this, "打开音乐文件", "", "音频文件 (*.mp3 *.wav *.ogg)");

      for (const QString &fileName : fileNames)
      {
          if (!music_list->addMedia(QUrl::fromLocalFile(fileName))) {
              qDebug() << "Failed to add media:" << fileName;
              continue;
          }
          qDebug() << "Added media:" << fileName;
      }

      if (!music_list->mediaCount())
      {
          qDebug() << "No media to play.";
          return;
      }
      int mediaCount = music_list->mediaCount();

      qDebug() << "歌曲总数:" << mediaCount;

      for(int index=0 ;index < mediaCount;index++)
      {
           QMediaContent mediaAt = music_list->media(index);
          if(true == add_Media_url(mediaAt.request().url()))
          {
              QListWidgetItem *item_temp = new QListWidgetItem(mediaAt.request().url().fileName());
              listWidget->addItem(item_temp);
          }
      }
     //  listWidget->show();
}

void widget_1::on_pushButton_pre_clicked()
{
    int ID_temp;
    ID_temp= play_Media.ID-1;
    play_Media= select_MediaUrlID(ID_temp);
    my_paly->setMedia(play_Media.Path);
    my_paly->play();
}

void widget_1::on_pushButton_next_clicked()
{

    int ID_temp;
    ID_temp= play_Media.ID+1;
    play_Media= select_MediaUrlID(ID_temp);
    my_paly->setMedia(play_Media.Path);
    my_paly->play();
    //QListWidgetItem *item_temp = new QListWidgetItem("下一个");
   // listWidget->addItem(item_temp);
  //  music_list->next();


    /*
    int mediaCount = music_list->mediaCount();

    qDebug() << "歌曲总数:" << mediaCount;
    for(int index=0 ;index < mediaCount;index++)
    {
        QMediaContent mediaAt = music_list->media(index);
        if (!mediaAt.isNull())
        {
            qDebug() << mediaAt.request().url(); // 打印该索引位置的媒体URL

        }
    }
*/
}
void widget_1::on_horizontalSlider_actionTriggered(int action)
{
    qDebug() << ui->horizontalSlider->value();
    // 设置播放进度
    // this->my_paly->setPosition(ui->horizontalSlider->value() * 100);

}
//音量进度条
void widget_1::on_verticalSlider_actionTriggered(int action)
{
    this->my_paly->setVolume(ui->verticalSlider->value());
}



void widget_1::play_music(QListWidgetItem *item)
{

    qDebug() <<" name "<< item->text();
    play_Media = select_MediaUrlByname(item->text());

    my_paly->setMedia(play_Media.Path);
    my_paly->play();
    qDebug() <<"ID:"<<play_Media.ID <<"url:" <<  play_Media.Path;

}
// 毫秒转分钟显示
QString widget_1::formatTime(qint64 milliseconds)
{
    qint64 seconds = milliseconds / 1000;
    qint64 minutes = seconds / 60;
    seconds = seconds % 60;
    return QString::asprintf("%lld:%02lld", minutes, seconds);
}
